﻿
//
//  Copyright (c) 2011 Extreme: Paweł Huryn (lead), Jakub Domański
//

using System;
using System.Web;

namespace Extreme.SPFramework.Presentation
{
    /// <summary>
    /// Base class for all user controls
    /// Contains Presentation Model property
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class UserControlBase<T> : System.Web.UI.UserControl
        where T : IPresentationModel, new()
    {
        private string stateKey = "BBB57B12-FE35-434f-A31C-4AE5D1A263AE" + typeof(T).FullName;

        /// <summary>
        /// Presentation model is stored at [PresentationModelSessionKey] key
        /// </summary>
        protected string StateKey
        {
            get { return stateKey; }
            set { stateKey = value; }
        }

        /// <summary>
        /// Presentation model stored in session. Otherwise, use ViewState
        /// </summary>
        protected bool StorePresentationModelInSession 
        { 
            get; 
            set; 
        }

        protected T PresentationModel 
        {
            get
            {
                var presentationModel = StorePresentationModelInSession ? Session[StateKey] : ViewState[StateKey];
                if (presentationModel == null || !presentationModel.GetType().IsAssignableFrom(typeof (T)))
                {
                    presentationModel = new T();
                    if(StorePresentationModelInSession)
                    {
                        Session[StateKey] = presentationModel;
                    }
                    else
                    {
                        ViewState[StateKey] = presentationModel;
                    }
                }
                return (T) presentationModel;
            }
            set
            {
                if (StorePresentationModelInSession)
                {
                    Session[StateKey] = value;
                }
                else
                {
                    ViewState[StateKey] = value;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            Page.Error += new EventHandler(Page_Error);
            base.OnInit(e);
        }

        protected string GetLocalResource(string resourceKey)
        {
            return Convert.ToString(HttpContext.GetLocalResourceObject(this.TemplateControl.AppRelativeVirtualPath, resourceKey));
        }

        private void Page_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            string message = string.Format("UNKNOWN_ERROR : FormControl.Page_Error, error = '{0}'.", ex.ToString());

            //LoggerHelper.LogError(message);

            //HttpContext.Current.Server.ClearError();
            //flowControl.GoToErrorPage(new Error(ex)); //TO_DO
        }
    }
}
